﻿import paho.mqtt.client as mqtt

client = mqtt.Client()

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to MQTT Broker!")
    else:
       print("Failed to connect, return code %d\n", rc)

def subscribe(topic):
    def on_message(client, userdata, msg):
        print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")

    client.subscribe(topic)
    client.on_message = on_message

def publish(topic, msg):
    result = client.publish(topic, msg)
    status = result[0]
    if status == 0:
        print(f"Send `{msg}` to topic `{topic}`")
    else:
        print(f"Failed to send message to topic {topic}")

if __name__ == '__main__':
    client.on_connect = on_connect
    # client.connect('127.0.0.1', 1883)
    client.connect('192.168.137.137', 1883)
    publish('mqtt/client', '1234567')
    subscribe('mqtt/server')
    client.loop_forever()